package d0904;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
// 方法类
import java.lang.reflect.Method;

public class Class类 {
    public static void main(String[] args) throws Exception {
        // Class 类的类, 获取类对象 3 个方法
        Class c1 = String.class;  // 类的静态属性  class
        Class c2 = Class.forName("java.lang.String");  // forName静态方法获取
        String s = "class";
        Class c3 = s.getClass();

        System.out.println(c1 == c2);
        System.out.println(c3 == c2);

        // 反射技术
        Student stu = new Student();
        stu.setName("张三");
        stu.setHeight(1.85f);
        stu.setGender('男');
        execute(stu);

    }


    static void execute(Object obj) throws InstantiationException,
            IllegalAccessException, NoSuchFieldException, SecurityException,
            NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

        Class cls = obj.getClass();

        System.out.println(cls);

        // 通过反射创建对象
        Object obj1 = cls.newInstance();
        System.out.println(obj1);

        // 从 cls 中或 name 属性
        Field f = cls.getDeclaredField("name");
        System.out.println("name 属性的类型是:" + f.getType());
        // 设置强制访问, private 也可以访问
        f.setAccessible(true);
        f.set(obj1, "张三");
        System.out.println(obj1);

        // 获取方法对象
        Method method = cls.getDeclaredMethod("setName", String.class);
        // 调用方法
        method.invoke(obj1, "李四");
        System.out.println(obj1);

    }
}
